package com.bing.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bing.entity.SendMsg.request.SmsSendRequest;
import com.bing.entity.SendMsg.response.SmsSendResponse;
import com.bing.mapper.SendMsgMapper;
import com.bing.service.SendMsgService;
import com.bing.utils.utilstool.ChuangLanSmsUtil;
import com.bing.utils.utilstool.HttpClientUtils;
import com.bing.utils.utilstool.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: Mr.HRL
 * @Description:
 * @Date: 2019-09-21 18:24
 * @Version: 1.0
 */
@Service
public class SendMsgServiceImpl implements SendMsgService {
    @Autowired
    SendMsgMapper sendMsgMapper;
    @Autowired
    RedisUtils redisUtils;

    @Value("${sms.url}")
    private String url;

    @Value("${sms.account}")
    private String account;

    @Value("${sms.password}")
    private String password;

    public final static String SMSTIMELIMIT = "SMSLIMIT";

    private static final String URL_SEND = "/smsJson.aspx"; //短信发送url
    private static final String URL_STATE_QUERY = "/statusJsonApi.aspx"; //短信状态报告url

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private final static Logger logger = LoggerFactory.getLogger(SendMsgServiceImpl.class);

    @Override
    public Map<String,Object> sendMsg(String phone) {
        Map<String, Object> map = new HashMap<String, Object>();

        //请求地址请登录253云通讯自助通平台查看或者询问您的商务负责人获取
        //String smsSingleRequestServerUrl = smsUrl;
        // 短信内容
        String count = getNum();

        String msg = "【多米借款】验证码: "+count+"，五分钟内有效。您正在进行登录/注册操作，请不要将验证码泄露给其他人！";
        //状态报告
        String report= "true";

        SmsSendRequest smsSingleRequest = new SmsSendRequest(account, password, msg, phone,report);
        String requestJson = JSON.toJSONString(smsSingleRequest);
        smsSingleRequest.setRequestText(requestJson);
        smsSingleRequest.setVerificaCode(count);
        sendMsgMapper.insert(smsSingleRequest);

        logger.info("before request string is: " + requestJson);

        String response = ChuangLanSmsUtil.sendSmsByPost(null, requestJson);

        logger.info("response after request result is :" + response);

        SmsSendResponse smsSingleResponse = JSON.parseObject(response, SmsSendResponse.class);
        smsSingleRequest.setCode(smsSingleResponse.getCode());
        smsSingleRequest.setErrorMsg(smsSingleResponse.getErrorMsg());
        smsSingleRequest.setMsgId(smsSingleResponse.getMsgId());
        smsSingleRequest.setResponseTime(new Date());
        smsSingleRequest.setResponseText(response);
        sendMsgMapper.updateMsgStatus(smsSingleRequest);
        if ("0".equals(smsSingleResponse.getCode())){
            map.put("state", true);
            map.put("message","发送成功");
        } else {
            map.put("state", false);
            map.put("message","发送失败:"+smsSingleResponse.getErrorMsg());
        }
        logger.info("response  toString is :" + smsSingleResponse);
        return map;
    }

    public String getNum(){
        String code="";
        Random rand=new Random();//生成随机数
        for(int a=0;a<6;a++){
            code+=rand.nextInt(10);//生成6位验证码
        }
        return code;
    }


    /**
     * 短信发送
     * @param mobile
     * @return
     */
    public Map<String,Object> sendSmsAutomatic(String mobile){
        Map<String, Object> map = new HashMap<String, Object>();
        if(!this.isMobiPhoneNum(mobile)){
            map.put("state", false);
            map.put("message","发送失败、错误代码:"+"机号格式不正确");
            return map;
        }
        //判断短信的是否已发送
       /* String key = SMSTIMELIMIT+mobile;
        if (redisUtils.haskey(SMSTIMELIMIT+mobile)) {
            map.put("state", false);
            map.put("message","短信已发送请稍后重试");
            return map;
        } else {
            redisUtils.set(key,mobile,60);
        }*/

        Date sendTime = new Date();
        String count = getNum();
        String msg = "【多米借款】验证码: "+count+"，五分钟内有效。您正在进行登录/注册操作，请不要将验证码泄露给其他人！";

        Map<String,String> param = new HashMap<>();
        param.put("account",account);
        param.put("password",password);
        param.put("mobile",mobile);
        param.put("content",msg);
        param.put("sendTime",sendTime!=null?sdf.format(sendTime):null);
        param.put("action","send");

        String requestClob = HttpClientUtils.getUrlParamsByStringMap(param);

        SmsSendRequest smsSingleRequest = new SmsSendRequest(account, password, msg, mobile,"send");
        smsSingleRequest.setRequestText(requestClob);
        smsSingleRequest.setVerificaCode(count);
        sendMsgMapper.insert(smsSingleRequest);
        //{"returnstatus":"Success","message":"操作成功","remainpoint":"16","taskID":"1909284657201003","successCounts":"1"}
        Map<String,String> result = HttpClientUtils.sendPurchaseReport(url,param);
        //Map<String,String> result = new HashMap<>();
       // result.put("requsetState","true");
        System.out.println(result.toString());
        if(result.get("requsetState").equals("true")){
            String conResult = result.get("clob");
           // String conResult = "{\"returnstatus\":\"Success\",\"message\":\"操作成功\",\"remainpoint\":\"16\",\"taskID\":\"1909284657201003\",\"successCounts\":\"1\"}";
            JSONObject sobj = JSONObject.parseObject(conResult);
            String returnstatus = sobj.getString("returnstatus");

            if(returnstatus.equals("Success")){
                String taskID = sobj.getString("taskID");
                //更新短信请求信息
                smsSingleRequest.setCode(returnstatus);
                smsSingleRequest.setErrorMsg(sobj.getString("message"));
                smsSingleRequest.setMsgId(taskID);
                smsSingleRequest.setResponseTime(new Date());
                smsSingleRequest.setResponseText(conResult);
                sendMsgMapper.updateMsgStatus(smsSingleRequest);
                map.put("state", true);
                map.put("message","发送成功");

            }else{
                //更新短信请求信息
                String message = sobj.getString("message");
                smsSingleRequest.setCode(returnstatus);
                smsSingleRequest.setErrorMsg(message);
                smsSingleRequest.setResponseTime(new Date());
                smsSingleRequest.setResponseText(conResult);
                sendMsgMapper.updateMsgStatus(smsSingleRequest);

                logger.error("调用短信发送接口异常，错误代码:"+message);
                map.put("state", false);
                map.put("message","发送失败、错误代码:"+message);
             //   redisUtils.delete(key);
            }

        }else{
            //更新短信请求信息
            String errorMsg = result.get("clob");
            smsSingleRequest.setCode("Fail");
            smsSingleRequest.setErrorMsg("调用短信发送接口异常");
            smsSingleRequest.setResponseTime(new Date());
            smsSingleRequest.setResponseText(errorMsg);
            sendMsgMapper.updateMsgStatus(smsSingleRequest);
            map.put("state", false);
            map.put("message","调用短信发送接口异常，错误代码:"+errorMsg);
            logger.error("调用短信发送接口异常，错误代码:"+errorMsg);
         //   redisUtils.delete(key);
        }
        return map;
    }

    /**
     * 通用判断
     * @param telNum
     * @return
     */
    private static boolean isMobiPhoneNum(String telNum){
        String regex = "^((11[0-9])|(12[0-9])|(16[0-9])|(17[0-9])|(19[0-9])|(13[0-9])|(10[0-9])|(14[0-9])|(15[0-9])|(18[0-9]))\\d{8}$";
        Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(telNum);
        return m.matches();
    }

}
